/**
 * The class PostfixCalculator calculates a given expression in postfix format
 * @author Michael Fildstein, ID: 309161594     
 * @author Tomer Ben Rachel ID: 021982475     
 */



public class PostfixCalculator {

	
		
 /**
 * The method evaluate receives an expression in string from, and calculates the value of that expression in these steps:
 * It turns the string into a series of tokens and while there are still tokens inside the string it:
 * Checks to see if the token is of ValueToken type or BinaryOp type.
 * If the token is of VslueToken type it inserts it into the stack
 * If the token is of BinaryOp type it pops out two elements from the stack and activates the arithmetic operation of the current
 * token on them and pushes the result back into the stack
 * @param expr A string data type representing the postfix expression
 * @return A double data type representing value of the postfix expression
 */  
	
	
	public double evaluate(String expr){    

    int stackSize;		
		ExpTokenizer string = new ExpTokenizer(expr);
		stackSize = string.countTokens();
		StackAsArray stack = new StackAsArray(stackSize);
		
		Object temp;
		ValueToken left;
		ValueToken right;
		double  ans;
		while (string.hasMoreElements()){
         temp = string.nextElement();
         if (temp instanceof ValueToken){  //If the token is a number
               stack.push(temp);
			   }else{
               right = (ValueToken)stack.pop(); //If the token is an arethmetic operation we need to pop the two top objects in the stack
				       left = (ValueToken)stack.pop();	//And apply the arethmetic operation on both of them
				       ans = ((BinaryOp)temp).operate(left.getValue(), right.getValue());
				       ValueToken tempRes = new ValueToken(ans);
				       stack.push(tempRes);
			        }
		    }  	
		return ((ValueToken)stack.pop()).getValue();   //Returning the final result 	
	}
	
}